{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Road data saved to road_data.osm\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import json\n",
    "\n",
    "def query_osm_highways_by_types_and_bbox(road_types, bbox):\n",
    "    overpass_url = \"http://overpass-api.de/api/interpreter\"\n",
    "    road_types_str = \"|\".join(road_types)\n",
    "    overpass_query = f\"\"\"\n",
    "        [out:xml];\n",
    "        way[\"highway\"~\"{road_types_str}\"]{bbox};\n",
    "        (._;>;);\n",
    "        out meta;\n",
    "        \"\"\"\n",
    "    response = requests.get(overpass_url, params={'data': overpass_query})\n",
    "    data = response.text\n",
    "    return data\n",
    "\n",
    "def save_osm_data_to_file(osm_data, filename):\n",
    "    with open(filename, 'w', encoding='utf-8') as f:\n",
    "        f.write(osm_data)\n",
    "\n",
    "def main():\n",
    "    road_types = [\"motorway\", \"motorway_link\"]  # 这里包含了 \"motorway\" 和 \"motorway_link\"这种特定等级的道路\n",
    "    bbox = \"(30.0923, 119.2244, 30.3284, 120.0901)\"  # 经纬度范围，(南部纬度, 西部经度, 北部纬度, 东部经度)\n",
    "    osm_data = query_osm_highways_by_types_and_bbox(road_types, bbox)\n",
    "    # 保存道路数据到.osm文件\n",
    "    save_osm_data_to_file(osm_data, 'road_data.osm')\n",
    "    print(\"Road data saved to road_data.osm\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
